package com.ff.javamonkey.ui;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ff.javamonkey.R;

public class ClientActivity extends Activity implements OnClickListener {
	// Debugging
	private final String TAG = "ClientActivity";
	
	// UI Components
	private EditText txtServerIp;
	private Button btnConnectPhone;
	private EditText txtClientMessage;
	private Button btnClientSend;
	private TextView txtClientStream;
	private TextView txtClientStatus;
	
	//private String serverIpAddress = "172.18.22.222";
	// this is sitc server
	private String serverIpAddress = "74.86.148.171";
	//private String serverIpAddress = "209.85.175.103";
	private boolean connected = false;
	private Handler handler = new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_client);
		txtClientMessage = (EditText)findViewById(R.id.txtEditClientMessage);
		btnClientSend = (Button)findViewById(R.id.btnClientSend);
		txtClientStream = (TextView)findViewById(R.id.txtClientStream);
		txtClientStatus = (TextView)findViewById(R.id.txtClientStatus);
		
		Thread clientThread = new Thread(new ClientThread());
		clientThread.start();
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		connected = false;
	}
	
	public void updateClientStatus(String status) {
		txtClientStatus.setText(status);
	}
	
	public class ClientThread implements Runnable {
		
		public void run() {
			try {
				InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
				final String serverHostNameString = serverAddr.getCanonicalHostName();
				Socket socket = new Socket(serverAddr, ServerActivity.SERVER_PORT);
				connected = true;
				handler.post(new Runnable() {
					public void run() {
						updateClientStatus("connected: " + serverHostNameString);
					}
				});
				while (connected) {
					try {
						Log.i(TAG, "Sending commmand");
						PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
						out.println("Hey server!");
					}
					catch (Exception ex) {
						Log.e(TAG, "Error.", ex);
					}
				}
				socket.close();
			}
			catch (Exception e) {
				final String eLocalizedMessage = e.getLocalizedMessage();
				Log.e(TAG, "Error.", e);
				handler.post(new Runnable() {
					public void run() {
						updateClientStatus("Not Connected. " + eLocalizedMessage);
					}
				});
				connected = false;
			}
		}
	}

	public void onClick(View v) {
		
	}
}
